<template>
  <div class="fromcom">
    <el-form :ref="refform" :model="form" :rules="rules" label-position="left" :inline="inlineshow" :class="{'queryform':inlineshow}" class="demo-form-inline "  label-width="110px">
        <el-form-item :class="{'clearBorder':clearBorder}" v-for="(item,index) in fromList" :key="item.value" :label="item.label" :prop="item.value">
          <span v-if="item.computed">{{Number(form[item.one] || 0)   - Number(form[item.two] || 0)}}</span>
          <!-- 输入框 -->
          <el-input  v-if="item.input" :type="item.inputType" @blur="tableBlur(form[item.value],item.blur,index,item.value)"  @input="(e)=>tableInput(e,item.zheng,index,item.value)" v-model="form[item.value]" clearable :disabled="item.disabled" />
          <!-- 时间选择器 -->
          <el-date-picker clearable  v-if="item.data"  v-model="form[item.value]" :disabled="item.disabled" type="date" value-format="timestamp"  />
          <!-- 单选框 -->
          <el-radio-group clearable  v-if="item.radio"  v-model="form[item.value]"  :disabled="item.disabled">
            <el-radio v-for="it in item.list" :key="it.value+returnRandom()" :label="it.value" :value="it.value">{{it.label}}</el-radio>
          </el-radio-group>
          <!-- 选择器 -->
          <el-select clearable  v-if="item.select" :multiple="item.multiple" :disabled="item.disabled"   @change="(e)=>remoteMethod(e,item.filter,true,index)" :filterable="item.filter || item.localFilter" :remote="item.localFilter ? false:item.filter" @focus="remoteMethod('',item.filter,false,index)" :remote-method="(e)=>remoteMethod(e,item.filter,false,index)" v-model="form[item.value]" >
              <el-option v-for="it in item.list" :key="it.value+returnRandom()" :label="it.label" :value="it.value" />
          </el-select>
          <!-- 级联选择器 -->
          <el-cascader v-if="item.cascader" v-model="form[item.value]" placeholder="请选择"  :options="item.list" :props="item.props" :show-all-levels="false" filterable></el-cascader>
          <!-- 上传图片 -->
          <el-upload
              @click.native="handlePreviewImage(item.disabled)"
              :disabled="item.disabled"
              v-if="item.upload"
              class="upload-demo"
              ref="upload"
              :action="actives"
              :headers="headers"
              :before-upload="beforeuploads"
              :on-remove="(file, fileList)=>handleRemove(file, fileList,item.value,item.limit)"
              :file-list="filelist"
              :http-request="(e)=>uploadSectionFile(e,item.value,item.limit)"
              :on-preview="handlePreview"
              :limit="item.limit || 1"
              accept=".jpeg,.png,.jpg"
              list-type="picture">
              <el-button size="small" type="primary">点击上传</el-button>
              <div slot="tip" class="el-upload__tip">只能上传{{item.limit || 1}}张图片且只能上传.jpeg,.png,.jpg文件，且不超过 10 M</div>
              <el-progress v-if="progressFlag" :percentage="loadProgress"></el-progress>
            </el-upload>
            <!-- 上传图片2 -->
          <el-upload
              @click.native="handlePreviewImage(item.disabled)"
              :disabled="item.disabled"
              v-if="item.uploadTwo"
              class="upload-demo"
              ref="uploadTwo"
              :action="actives"
              :headers="headers"
              :before-upload="beforeuploadsTwo"
              :on-remove="(file, fileList)=>handleRemoveTwo(file, fileList,item.value,item.limit)"
              :file-list="filelistTwo"
              :http-request="(e)=>uploadSectionFileTwo(e,item.value,item.limit)"
              :on-preview="handlePreview"
              :limit="item.limit || 1"
              accept=".jpeg,.png,.jpg"
              list-type="picture">
              <el-button size="small" type="primary">点击上传</el-button>
              <div slot="tip" class="el-upload__tip">只能上传{{item.limit || 1}}张图片且只能上传.jpeg,.png,.jpg文件，且不超过 10 M</div>
              <el-progress v-if="progressFlagTwo" :percentage="loadProgressTwo"></el-progress>
            </el-upload>
            <!-- 上传文件 -->
          <el-upload
              :disabled="item.disabled"
              v-if="item.uploadFile"
              class="upload-demo"
              ref="upload"
              drag
              :action="actives"
              :headers="headers"
              :before-upload="beforeuploads"
              :on-remove="handleRemoveFile"
              :file-list="uploadFilelist"
              :http-request="uploadFile"
              :on-preview="handlePreview"
              :limit="1"
              :accept="item.accept"
              list-type="fileList">
              <i class="el-icon-upload"></i>
              <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
              <div class="el-upload__tip" slot="tip">只能上传{{item.accept}}文件，且不超过 10 M</div>
            </el-upload>
          <div v-show="item.checkboxs">
            <el-checkbox  v-for="it in item.list" :disabled="it.disabled" :key="it.value+returnRandom()" v-model="form[it.value]">{{it.label}}</el-checkbox>
          </div>
        </el-form-item>
      </el-form>
       <!-- 图片缩放 -->
    <dialogImg :dialogimgShow="dialogimgShow" @changeShow="(e)=>dialogimgShow = e" :imgList="imgList"></dialogImg>
  </div>
</template>

<script>
import dialogImg from '@/views/components/dialogImg';
export default {
  components:{dialogImg},
  data(){
    return{
      actives: process.env.VUE_APP_BASE_API+'/pc/file/upload',
      headers:{Authorization: 'Bearer ' + localStorage.getItem('ACCESS_TOKEN')} ,
      form:this.paramsform,
      filelist:[], // 图片数组
      filelistTwo:[], // 图片数组2
      uploadFilelist:[],// 文件数组
      loadProgress: 0, // 动态显示进度条
      progressFlag: false, // 关闭进度条
      loadProgressTwo: 0, // 动态显示进度条2
      progressFlagTwo: false, // 关闭进度条2
      timer:null, // 进度条
      dialogimgShow:false, // 控制是否展示图片
      imgList:[],
    }
  },
  props:{
    paramsform:{   // 
      type:Object,
      default:()=>({})
    },
    fromList:{  //form 数组 主要内容
      type:Array,
      default:()=>[] // input：输入框 data：时间 radio：单选框 select：选择器 upload：图片上传 checkboxs:复选框
    },
    inlineshow:{   // 是否让el-form 横向展示
      type:Boolean,
      default:false
    },
    rules:{  // 校验规则
      type:Object,
      default:()=>({})
    },
    refform:{   // ref的值
      type:String,
      default:'form'
    },
    clearBorder:{  // 判断是否消除边框
      type:Boolean,
      default:false
    },
  },
  watch:{
    // paramsform (newValue, oldValue){
    //   // console.log(this.paramsform,1111)
    //   this.form = this.paramsform
    //   if(this.form.filelist) this.filelist = this.form.filelist
    //   if(this.form.uploadFilelist) this.filelist = this.form.uploadFilelist
      
    // },
    paramsform:{
      handler(){
        this.form = this.paramsform ?? {}
        if(this.form.filelist) this.filelist = this.form.filelist ?? []
        if(this.form.filelistTwo) this.filelistTwo = this.form.filelistTwo ?? []
        if(this.form.uploadFilelist) this.uploadFilelist = this.form.uploadFilelist ?? []
      }
    },
    form (newValue, oldValue){
      this.$emit('update:paramsform', newValue)
    },
  },
  created(){
    this.form = this.paramsform ?? {}
    if(this.form.filelist) this.filelist = this.form.filelist ?? []
    if(this.form.filelistTwo) this.filelistTwo = this.form.filelistTwo ?? []
    if(this.form.uploadFilelist) this.uploadFilelist = this.form.uploadFilelist ?? []
    
  },
  updated(){
    // 清除校验效果
    if(Object.keys(this.rules).length !== 0){
      this.$refs[this.refform].clearValidate()
    }
  },
  methods:{
    uploadSectionFile(val,imgValue,limit){ // 上传图片
      // 开启进度条
      this.progressFlag = true; // 显示进度条
      this.loadProgress = 0
      this.timer = setInterval(()=>{
        if(this.loadProgress === 99) return
        this.loadProgress += 1
      },100)
      let file = val.file
      // 根据后台需求数据格式 
      const form = new FormData();
      // 文件对象
      form.append("multipartFile", file);
      // 本例子主要要在请求时添加特定属性，所以要用自己方法覆盖默认的action
      // form.append("clientType", 'xxx');
      // 项目封装的请求方法，下面做简单介绍
      this.$axios({url:'/pc/file/upload',method:'post',data:form}).then(res => {
            // 关闭进度条
            this.loadProgress = 100
            clearInterval(this.timer)
            this.progressFlag = false;
            this.form.img = res.data
            if(limit && limit > 1){
              if(this.form[imgValue] instanceof Array && this.form[imgValue].length > 0){
                this.form[imgValue] = []
                this.form[imgValue].push({url:res.data,name:res.data})
              }else{
                this.form[imgValue] = [{url:res.data,name:res.data}]
              }
            }else{
              this.$set(this.form,imgValue,res.data)
            }
            // this.filelist = [{url:res.data,name:res.data}]
            this.filelist.push({url:res.data,name:res.data})
            this.form.filelist = this.filelist
            this.$message.success('上传成功')
        })
        .catch(() => {
          // xxx
          // 关闭进度条
          this.loadProgress = 100
          clearInterval(this.timer)
          this.progressFlag = false;
        });
    },
    uploadSectionFileTwo(val,imgValue,limit){ // 上传图片2
      // 开启进度条
      this.progressFlagTwo = true; // 显示进度条
      this.loadProgressTwo = 0
      this.timer = setInterval(()=>{
        if(this.loadProgressTwo === 99) return
        this.loadProgressTwo += 1
      },100)
      let file = val.file
      // 根据后台需求数据格式 
      const form = new FormData();
      // 文件对象
      form.append("multipartFile", file);
      // 本例子主要要在请求时添加特定属性，所以要用自己方法覆盖默认的action
      // form.append("clientType", 'xxx');
      // 项目封装的请求方法，下面做简单介绍
      this.$axios({url:'/pc/file/upload',method:'post',data:form}).then(res => {
            // 关闭进度条
            this.loadProgressTwo = 100
            clearInterval(this.timer)
            this.progressFlagTwo = false;
            if(limit && limit > 1){
              if(this.form[imgValue] instanceof Array && this.form[imgValue].length > 0){
                this.form[imgValue] = []
                this.form[imgValue].push({url:res.data,name:res.data})
              }else{
                this.form[imgValue] = [{url:res.data,name:res.data}]
              }
            }else{
              this.$set(this.form,imgValue,res.data)
            }
            this.filelistTwo.push({url:res.data,name:res.data})
            this.$message.success('上传成功')
        })
        .catch(() => {
          // xxx
          // 关闭进度条
          this.loadProgressTwo = 100
          clearInterval(this.timer)
          this.progressFlagTwo = false;
        });
    },
    uploadFile(val){  // 上传文件
      let file = val.file
      // 根据后台需求数据格式
      const form = new FormData();
      // 文件对象
      form.append("multipartFile", file);
      this.$axios({url:'/pc/file/upload',method:'post',data:form}).then(res => {
            this.form.fileUrl = res.data
            this.uploadFilelist = [{url:res.data,name:res.data}]
            this.form.uploadFilelist = this.uploadFilelist
            this.$message.success('上传成功')
      })
      .catch(() => {
        // xxx
      });
    },
    handlePreviewImage(disabled){//在详情点击图片,进行图片放大操作
      if(!disabled) return
      const urls = this.filelist.map(item=>item.url) ?? []
      if( urls.length === 0) return 
      this.imgList = urls
      this.dialogimgShow = true
    },
    handlePreview(file){//点击文件列表中已上传的文件时的钩子,进行下载
      let link = document.createElement("a"); //定义一个a标签
      link.download = file.name; //下载后的文件名称
      link.href = file.url; //需要生成一个 URL 来实现下载
      link.click(); //模拟在按钮上实现一次鼠标点击
      window.URL.revokeObjectURL(link.href);
    },
    // 上传之前
    beforeuploads(file){
      this.$refs.upload.forEach((item,index)=>{
        this.$refs.upload[index].clearFiles();
      })
      let size = file.size / 1024 / 1024 ;
      if(size > 10){
        this.$message.warning('大小不能超过 10 M')
        return false
      } 
      
      // this.$refs.upload.clearFiles(); //上传成功之后清除历史记录
    },
    // 上传之前2
    beforeuploadsTwo(file){
      this.$refs.uploadTwo.forEach((item,index)=>{
        this.$refs.uploadTwo[index].clearFiles();
      })
      let size = file.size / 1024 / 1024 ;
      if(size > 10){
        this.$message.warning('大小不能超过 10 M')
        return false
      } 
      
      // this.$refs.upload.clearFiles(); //上传成功之后清除历史记录
    },
    // 移除图片时
    handleRemove(file, fileList,value,limit){
      this.filelist = fileList
      this.form.img = ''//弃用但是怕有地方使用
      if(limit && limit > 1){
        this.form[value] = fileList
      }else{
        this.$set(this.form,value,'')
      }
      this.form.filelist = this.filelist
    },
    handleRemoveTwo(file, fileList,value,limit){// 移除图片时2
      this.filelistTwo = fileList
      this.form.img = '' //弃用但是怕有地方使用
      if(limit && limit > 1){
        this.form[value] = fileList
      }else{
        this.$set(this.form,value,'')
      }
    },
     // 移除文件时
    handleRemoveFile(file, fileList){
      this.uploadFilelist = fileList
      this.form.uploadFilelist = this.uploadFilelist
      this.form.fileUrl = ''
    },
    remoteMethod(e,val,changes,index){   // 下拉框远程搜索方法
      if(val){
        if(changes) return this.$emit('remoteMethods',e,true,index)
        this.$emit('remoteMethods',e,false,index)
      }
    },
    tableInput(e,pan,index,name){ // input框，input事件
      // 只取正数
      if(pan){
        if(e.indexOf('0') == 0 && e.length > 1)this.$set(this.form,name,e.substring(1,a.length))
          
        if(Number(e) < 0) this.$set(this.form,name,0)
      }
    },
    tableBlur(e,pan,index,value){  // input blur 事件
      if(pan){
        this.$emit('tableBlurs',e,index,value)
      }
    },
    returnRandom(){ // 生成随机数
      return Math.random()
    }
  }
}
</script>

<style scoped lang="scss">
.queryform{
  // padding: 20px;
  .el-form-item{
    width: 45%;
    text-align: center;
  }
}
.clearBorder{
  ::v-deep .el-input--medium .el-input__inner{
    border: none;
  }
}

</style>